package com.example.buxiaorui.studentsystem;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import java.lang.Math;

import static java.lang.Math.random;

public class SqlDao {
    private SqlOpenHelper sqlOpenHelper;
    public SqlDao(Context context) {
            sqlOpenHelper=new SqlOpenHelper(context);
    }

    public boolean checkdata(String username){
        boolean res=false;
        SQLiteDatabase sqLiteDatabase=sqlOpenHelper.getWritableDatabase();
        Cursor cursor=sqLiteDatabase.rawQuery("select password from managers where username=?",new String[]{username});
        if (cursor.moveToNext()){
            res=true;
        }
        sqLiteDatabase.close();
        cursor.close();
        return res;
    }
    public int addManager(String username,String password,int code){
        //status为0，添加失败
        int status=0;
        //先查询是否存在用户
        boolean res=checkdata(username);
        SQLiteDatabase sqLiteDatabase=sqlOpenHelper.getWritableDatabase();
        if (res==false){
            sqLiteDatabase.execSQL("insert into managers (username,password,code) values (?,?,?)",new Object[]{username,password,code});
            status=1;
        }
        sqLiteDatabase.close();
        //返回status
        return status;
    }

    //检查邀请码是否存在
    public boolean checkCode(String code){
        boolean res=false;
        SQLiteDatabase sqLiteDatabase=sqlOpenHelper.getWritableDatabase();
        Cursor cursor=sqLiteDatabase.rawQuery("select username from managers where code=?",new String[]{code});
        if (cursor.moveToNext()){
            res=true;
        }
        sqLiteDatabase.close();
        cursor.close();
        return res;
    }
    //获取密码
    public String getPassword(String username){
        String password="";
        SQLiteDatabase sqLiteDatabase=sqlOpenHelper.getWritableDatabase();
        Cursor cursor=sqLiteDatabase.rawQuery("select password from managers where username=?",new String[]{username});
        if (cursor.moveToNext()){
            password=cursor.getString(0);
        }
        return password;
    }
}
